import React, {Component} from 'react';
import { Form, Input, InputNumber, Modal, Pagination, Space } from "antd";
import TheButton from "@/components/TheButton";
import TheTable from "@/components/TheTable";
import TheImage from '@/components/TheImage';
import { apiGetUserList, } from '@/request/users';
import { sheet2Excel } from '@/utils/table2Excel.js';
import _ from 'lodash';
import "../../couponsList/style.scss";

class User extends Component {
    constructor(props) {
        super(props)
        this.formRef = React.createRef()
        this.state = {
            isModalShow: false,
            selectedUserSource: [],
            selectedPageData: {
                pageNo: 1,
                pageSize: 10,
                totalCount: 0,
            },
            searchForm: {
                name: '',
            },
            userList: [],
            userListPage: {
                pageNo: 1,
                pageSize: 10,
                totalCount: 0,
            },
            dataSourceCopy: [],
            couponTableColumns: [{
                title: '用户id',
                dataIndex: 'memberId',
                key: 'memberId',
            },{
                title: '头像',
                dataIndex: 'memberAvatar',
                key: 'memberAvatar',
                render: (text) => {
                    if (text) {
                        let str = text.split(',')[0]
                        return <div>
                            {
                                text.split(',').map(item => <span style={{ marginRight: 10 }}><TheImage src={item} width={80} height={80} /></span>)
                            }
                        </div>
                    }
                }
            },{
                title: '昵称',
                dataIndex: 'nickName',
                key: 'nickName',
            },{
                title: '手机号',
                dataIndex: 'memberMobile',
                key: 'memberMobile',
            },{
                title: '身份',
                dataIndex: 'memberType',
                key: 'memberType',
                render: (text, render) => {
                    let label = ''
                    switch (text) {
                      case 'R':
                        label = '注册会员'
                        break;
                      case "P":
                        label = '正式会员'
                        break;
                      case "S":
                        label = "商户会员"
                        break;
                      default:
                        label = "返回值错误"
                    }
                    return label;
                  }
            },{
                title: '状态',
                dataIndex: 'memberStatus',
                key: 'memberStatus',
                render: text => {
                    let label = ''
                    switch (text) {
                      case 'Y':
                        label = '正常'
                        break
                      case 'N':
                        label = '冻结'
                        break
                      default:
                        label = '返回值错误'
                        break
                    }
                    return label;
                }
            },{
                title: '注册时间',
                dataIndex: 'memberCreatedTime',
                key: 'memberCreatedTime',
            }],
            fileList:[],
            loading:false
        }
    }
    componentDidMount() {
        this.getData()
    }

    getData = async (value)=>{
        const { userListPage } = this.state
        let res = await apiGetUserList({...userListPage, memberStatus:'Y', ...value })
        if(res.code === 0){
            this.setState({
                userList: res.data,
                userListPage: {
                    pageNo: res.pageNo,
                    pageSize: res.pageSize,
                    totalCount: res.totalCount,
                },
            })
        }
    }
    // 选择弹框
    openModal() {
        this.setState({
            isModalShow: true,
            dataSourceCopy: [...this.state.selectedUserSource]
        }, () => {
            this.getSelectKeys()
            this.resetForm()
        })
    }
    // 选择商品保存
    handleOk = () => {
        this.setState({
            isModalShow: false,
            selectedUserSource: this.state.dataSourceCopy
        },()=>{
            this.props.setData(this.state.selectedUserSource)
        })
    }
    // 选择商品取消
    handleCancel = () => {
        this.setState({
            isModalShow: false
        })
    }
    // 获取当前勾选得key
    getSelectKeys() {
        const selectedRowKeys = this.state.dataSourceCopy.map(item => item.memberId)
        this.setState({
            selectedRowKeys
        })
    }
    //批量勾选
    onSelect = (record, selected, selectedRows) => {
        let dataSourceCopy = [...this.state.dataSourceCopy]
        if (selected) {
            dataSourceCopy.push({ ...record })
        } else {
            const delIndex = dataSourceCopy.findIndex(item => item.memberId === record.memberId)
            dataSourceCopy.splice(delIndex, 1)
        }
        this.setState({
            dataSourceCopy
        }, () => this.getSelectKeys())
    }
    // 勾选全部
    onSelectAll = (selected, rows, newRow) => {
        let dataSourceCopy = [...this.state.dataSourceCopy]
        if (selected) {
            dataSourceCopy = dataSourceCopy.concat(...newRow)
        } else {
            const newKeys = newRow.map(item => item.memberId)
            dataSourceCopy = dataSourceCopy.filter(item => !newKeys.includes(item.memberId))
        }
        this.setState({
            dataSourceCopy
        }, () => this.getSelectKeys())
    }
    // 选择内容分页
    selectedPageChange(e) {
        this.state.selectedPageData.pageNo = e
        this.setState({
            selectedPageData: this.state.selectedPageData
        })
    }
    // 弹框分页
    userListPageChange(e) {
        this.state.userListPage.pageNo = e
        this.setState({
            userListPage: this.state.userListPage
        }, () => {
            this.getData()
        })
    }
    // 弹框搜索
    searchGoods() {
        const values = this.formRef.current.getFieldsValue()
        _.forIn(values, (v, k) => {
            if (v === undefined || v === '' || v === null) {
                delete (values[k])
            }
        })
        this.setState({
            searchForm: values,
            userListPage: {
                pageNo: 1,
                pageSize: this.state.userListPage.pageSize,
                totalCount: 0
            }
        }, () => this.getData(this.state.searchForm))
    }
    // 弹框重置
    resetForm() {
        this.formRef.current.resetFields()
        this.setState({
            searchForm: {
                name: '',
            }
        }, () => this.getData())
    }
    // 导入
    upload = async (e)=>{
        let formData = new FormData()
        formData.append('file', e.target.files[0])
        console.log(e.target.files[0]);
        console.log(formData);
        e.target.value = ''
        fetch(React.$BaseUrl + '/trade/couponTimerCenter/uploadExcel',{
            method: "post",
            headers: {
                RSnetToken: sessionStorage.getItem('RSnetToken')
            },
            body: formData,
        })
        .then((res) => {
            this.setState({loading:true})
            res.json().then(result => {
                if (result.code === 0) {
                    this.setState({
                        selectedUserSource:result.data,
                        dataSourceCopy:result.data,
                        loading:false
                    },()=>this.props.setData(this.state.selectedUserSource))
                } else {
                    React.$message ({
                        type: 'error',
                        content: '导入错误，错误码：'+ result.code
                    })
                    this.setState ({
                        loading:false
                    })
                }
            })

        })
        .catch((err) => {
            React.$message({
                type: 'error',
                content: '导入失败'
            })
            this.setState({loading:false})
        })

    }
    // 下载模板
    downloadDemo() {
        // const { dataSource } = this.state
        // const { mode } = this.props
        // const a = document.createElement('a')
        // a.href = 'https://hqmimage.oss-cn-beijing.aliyuncs.com/%E6%96%B0%E5%A2%9E%E7%A7%92%E6%9D%80%E5%95%86%E5%93%81%E6%A8%A1%E6%9D%BF.xlsx'
        // document.body.append(a)
        // a.click()
        // a.remove()
        let fileName = '用户表'
        let tH_data = [
            { prop: 'memberId', title: '用户ID' },
            { prop: 'memberMobile', title: '用户手机号' },
        ]
        let tB_data = []
        sheet2Excel({tH_data, tB_data, fileName})
    }
    // 删除
    del = (record, index)=> {
        const dataSource = [...this.state.selectedUserSource]
        const {pageNo,pageSize} = this.state.selectedPageData
        dataSource.splice((pageNo-1)*pageSize+index, 1)
        this.setState({
            selectedUserSource: dataSource
        },()=>{
            this.props.setData(this.state.selectedUserSource)
        })
    }
    render() {
        let {
            isModalShow,
            selectedUserSource,
            selectedPageData,
            couponTableColumns,
            userListPage,
            selectedRowKeys,
            userList,
            loading
        } = this.state;
        const rowSelection = {
            selectedRowKeys,
            onSelect: this.onSelect,
            onSelectAll: this.onSelectAll,
        };

        return (
            <div className='noCanJoinGood'>
                <Space>
                    <TheButton size="middle" onClick={() => this.openModal()}>选择用户</TheButton>
                    <TheButton size="middle" className="goodsImport" >
                        <input type="file" className="importBtn" onChange={(e) => this.upload(e)} /> 批量导入
                    </TheButton>
                    {/* <Upload {...props}>
                        <TheButton size="middle" onClick={() => this.upload()} >批量导入</TheButton>
                    </Upload> */}
                    <TheButton type="link" size="middle" className="downloadDemo" onClick={() => this.downloadDemo()}>
                        下载导入文件模板
                    </TheButton>
                </Space>
                <TheTable loading={loading} dataSource={selectedUserSource} bordered size="middle"
                        pagination={{
                            showTotal: () => `共${selectedUserSource.length}条`,
                            pageSize: selectedPageData.pageSize,
                            onChange: (e) => this.selectedPageChange(e)
                        }}
                        columns={[...couponTableColumns,{
                            title: "操作",
                            fixed: "right",
                            width: 200,
                            render: (text, render, index) => {
                                return <TheButton onClick={() => this.del(render, index)}>删除</TheButton>
                            },
                        }]}
                          rowKey={(record) => record.couponId}
                ></TheTable>
                <Modal
                    width={'80%'} title={'选择用户'} visible={isModalShow} onOk={this.handleOk} onCancel={this.handleCancel}>
                    <Form layout={'inline'} ref={this.formRef} >
                        <Form.Item name="memberId" label='用户id'>
                            <InputNumber placeholder="用户id" style={{ width: 300 }}/>
                        </Form.Item>
                        <Form.Item name="wxNickName" label='用户昵称'>
                            <Input placeholder="用户昵称" style={{ width: 300 }}/>
                        </Form.Item>
                        <Form.Item>
                            <Space>
                                <TheButton size="middle" type="primary" onClick={() => this.searchGoods()}>查询</TheButton>
                                <TheButton size="middle" type="default" onClick={() => this.resetForm()}>重置</TheButton>
                            </Space>
                        </Form.Item>
                    </Form>
                    <TheTable
                        style={{ margin: '10px 0' }}
                        scroll={{ x: "max-content", y: '57vh' }}
                        columns={couponTableColumns}
                        dataSource={userList}
                        rowSelection={rowSelection}
                        rowKey={(record) => record.memberId}
                    />
                    <Pagination style={{ textAlign: 'right' }} size="small"
                                current={userListPage.pageNo}
                                total={userListPage.totalCount}
                                showSizeChanger={false}
                                onChange={this.userListPageChange.bind(this)}
                    />
                </Modal>
            </div>
        );
    }
}

export default User;
